package com.fjnu.dao;

import com.fjnu.dto.ArticleConditionDto;
import com.fjnu.dto.ArticleUpdateDto;
import com.fjnu.entity.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Repository
public class ArticleDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 新增文章
    public int insert(Article article) {
        if (article.getUserId() == null || article.getTitle() == null
                || article.getContent() == null || article.getCategoryId() == null) {
            return 0;
        }
        String sql = "INSERT INTO article(user_id, title, content, category_id, status, create_time) " +
                "VALUES(?, ?, ?, ?, ?, NOW())";
        return jdbcTemplate.update(sql,
                article.getUserId(),
                article.getTitle(),
                article.getContent(),
                article.getCategoryId(),
                article.getStatus() == null ? 0 : article.getStatus());
    }

    // 查询最新插入的文章（用于获取自增ID）
    public Article selectLastInserted(Integer userId, String title) {
        String sql = "SELECT * FROM article WHERE user_id = ? AND title = ? ORDER BY id DESC LIMIT 1";
        try {
            return jdbcTemplate.queryForObject(sql,
                    new BeanPropertyRowMapper<>(Article.class),
                    userId, title);
        } catch (Exception e) {
            return null;
        }
    }

    // 根据ID查询文章
    public Article selectById(Integer id) {
        String sql = "SELECT * FROM article WHERE id = ?";
        try {
            return jdbcTemplate.queryForObject(sql,
                    new BeanPropertyRowMapper<>(Article.class), id);
        } catch (Exception e) {
            return null;
        }
    }

    // 条件查询总数
    public Long countByCondition(ArticleConditionDto condition) {
        StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM article WHERE 1=1");
        List<Object> params = new ArrayList<>();
        if (condition.getTitle() != null) {
            sql.append(" AND title LIKE ?");
            params.add("%" + condition.getTitle() + "%");
        }
        if (condition.getContent() != null) {
            sql.append(" AND content LIKE ?");
            params.add("%" + condition.getContent() + "%");
        }
        if (condition.getCategoryId() != null) {
            sql.append(" AND category_id = ?");
            params.add(condition.getCategoryId());
        }
        if (condition.getStatus() != null) {
            sql.append(" AND status = ?");
            params.add(condition.getStatus());
        }
        return jdbcTemplate.queryForObject(sql.toString(), Long.class, params.toArray());
    }

    // 条件分页查询
    public List<Article> selectByCondition(ArticleConditionDto condition, int offset, int pageSize) {
        StringBuilder sql = new StringBuilder("SELECT * FROM article WHERE 1=1");
        List<Object> params = new ArrayList<>();
        if (condition.getTitle() != null) {
            sql.append(" AND title LIKE ?");
            params.add("%" + condition.getTitle() + "%");
        }
        if (condition.getContent() != null) {
            sql.append(" AND content LIKE ?");
            params.add("%" + condition.getContent() + "%");
        }
        if (condition.getCategoryId() != null) {
            sql.append(" AND category_id = ?");
            params.add(condition.getCategoryId());
        }
        if (condition.getStatus() != null) {
            sql.append(" AND status = ?");
            params.add(condition.getStatus());
        }
        sql.append(" LIMIT ?, ?");
        params.add(offset);
        params.add(pageSize);
        return jdbcTemplate.query(sql.toString(),
                new BeanPropertyRowMapper<>(Article.class),
                params.toArray());
    }

    // 更新文章状态
    public int updateStatus(Integer articleId, Integer status) {
        String sql = "UPDATE article SET status = ? WHERE id = ?";
        return jdbcTemplate.update(sql, status, articleId);
    }

    // 批量更新文章状态
    public int batchUpdateStatus(List<Integer> ids, Integer newStatus) {
        if (ids == null || ids.isEmpty() || newStatus == null || (newStatus != 0 && newStatus != 1)) {
            return 0;
        }
        StringBuilder sql = new StringBuilder("UPDATE article SET status = ? WHERE id IN (");
        List<Object> params = new ArrayList<>();
        params.add(newStatus);
        for (int i = 0; i < ids.size(); i++) {
            sql.append("?,");
            params.add(ids.get(i));
        }
        sql.deleteCharAt(sql.length() - 1);
        sql.append(")");
        return jdbcTemplate.update(sql.toString(), params.toArray());
    }

    // 根据DTO更新文章
    public int updateByDto(ArticleUpdateDto updateDto) {
        if (updateDto.getId() == null) {
            return 0;
        }
        StringBuilder sql = new StringBuilder("UPDATE article SET ");
        List<Object> params = new ArrayList<>();
        if (updateDto.getTitle() != null) {
            sql.append("title = ?,");
            params.add(updateDto.getTitle());
        }
        if (updateDto.getContent() != null) {
            sql.append("content = ?,");
            params.add(updateDto.getContent());
        }
        if (updateDto.getCategoryId() != null) {
            sql.append("category_id = ?,");
            params.add(updateDto.getCategoryId());
        }
        // 移除最后一个逗号
        if (sql.charAt(sql.length() - 1) == ',') {
            sql.deleteCharAt(sql.length() - 1);
        } else {
            return 0; // 无更新内容
        }
        sql.append(" WHERE id = ?");
        params.add(updateDto.getId());
        return jdbcTemplate.update(sql.toString(), params.toArray());
    }

    // 删除文章
    public int delete(Integer articleId) {
        String sql = "DELETE FROM article WHERE id = ?";
        return jdbcTemplate.update(sql, articleId);
    }
}